package com.zzw.mvvm.repository.net;

import com.zzw.mvvm.base.Constants;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpRequest {
    private static ApiService apiService;
    private static OkHttpClient okHttpClient = null;

    public static ApiService getApiService() {
        if (apiService == null) {
            synchronized (HttpRequest.class) {
                createOkHttpClient();
                createRetrofit();
            }
        }
        return apiService;
    }

    private static void createOkHttpClient() {
        okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(Constants.DEFAULT_TIME, TimeUnit.SECONDS)//设置读取超时时间
                .connectTimeout(Constants.DEFAULT_TIME, TimeUnit.SECONDS)//设置请求超时时间
                .writeTimeout(Constants.DEFAULT_TIME, TimeUnit.SECONDS)//设置写入超时时间
                .addInterceptor(new LogInterceptor())//添加打印拦截器
                .retryOnConnectionFailure(true)//设置出现错误进行重新连接。
                .build();
    }

    private static void createRetrofit() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.WEB_HOST)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        apiService = retrofit.create(ApiService.class);
    }
}
